import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:exif/exif.dart';
import 'package:flutter_video_info/flutter_video_info.dart';

class MetadataExtractor {
  // 照片EXIF提取器
  static Future<Map<String, dynamic>?> extractPhotoMetadata(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) return null;

      final bytes = await file.readAsBytes();
      final data = await readExifFromBytes(bytes);

      if (data.isEmpty) return null;

      // 提取关键EXIF信息
      final metadata = <String, dynamic>{};

      // 相机信息
      if (data.containsKey('Image Make')) {
        metadata['camera_make'] = data['Image Make']!.printable;
      }
      if (data.containsKey('Image Model')) {
        metadata['camera_model'] = data['Image Model']!.printable;
      }

      // 拍摄参数
      if (data.containsKey('EXIF FocalLength')) {
        final focalLength = data['EXIF FocalLength']!.printable;
        metadata['focal_length'] = _parseFraction(focalLength);
      }

      if (data.containsKey('EXIF FNumber')) {
        final aperture = data['EXIF FNumber']!.printable;
        metadata['aperture'] = _parseFraction(aperture);
      }

      // 尝试多个ISO字段
      if (data.containsKey('EXIF ISOSpeedRatings')) {
        final iso = data['EXIF ISOSpeedRatings']!.printable;
        metadata['iso'] = int.tryParse(iso);
      } else if (data.containsKey('EXIF PhotographicSensitivity')) {
        final iso = data['EXIF PhotographicSensitivity']!.printable;
        metadata['iso'] = int.tryParse(iso);
      }

      if (data.containsKey('EXIF ExposureTime')) {
        metadata['shutter_speed'] = data['EXIF ExposureTime']!.printable;
      }

      // 镜头信息
      if (data.containsKey('EXIF LensMake')) {
        metadata['lens_make'] = data['EXIF LensMake']!.printable;
      }
      if (data.containsKey('EXIF LensModel')) {
        metadata['lens_model'] = data['EXIF LensModel']!.printable;
      }

      // 图片尺寸
      if (data.containsKey('EXIF ExifImageWidth')) {
        final width = data['EXIF ExifImageWidth']!.printable;
        metadata['width'] = int.tryParse(width);
      }
      if (data.containsKey('EXIF ExifImageLength')) {
        final height = data['EXIF ExifImageLength']!.printable;
        metadata['height'] = int.tryParse(height);
      }

      // 如果没有EXIF尺寸，尝试从Image标签获取
      if (metadata['width'] == null && data.containsKey('Image ImageWidth')) {
        final width = data['Image ImageWidth']!.printable;
        metadata['width'] = int.tryParse(width);
      }
      if (metadata['height'] == null && data.containsKey('Image ImageLength')) {
        final height = data['Image ImageLength']!.printable;
        metadata['height'] = int.tryParse(height);
      }

      // GPS信息
      if (data.containsKey('GPS GPSLatitude') && data.containsKey('GPS GPSLatitudeRef')) {
        final lat = _parseGPS(
          data['GPS GPSLatitude']!.printable,
          data['GPS GPSLatitudeRef']!.printable,
        );
        if (lat != null) metadata['gps_latitude'] = lat;
      }

      if (data.containsKey('GPS GPSLongitude') && data.containsKey('GPS GPSLongitudeRef')) {
        final lng = _parseGPS(
          data['GPS GPSLongitude']!.printable,
          data['GPS GPSLongitudeRef']!.printable,
        );
        if (lng != null) metadata['gps_longitude'] = lng;
      }

      // 拍摄时间
      if (data.containsKey('EXIF DateTimeOriginal')) {
        final dateStr = data['EXIF DateTimeOriginal']!.printable;
        final dateTime = _parseExifDateTime(dateStr);
        if (dateTime != null) {
          metadata['date_taken'] = dateTime.millisecondsSinceEpoch;
        }
      }

      return metadata.isNotEmpty ? metadata : null;
    } catch (e) {
      debugPrint('提取EXIF信息失败: $filePath - $e');
      return null;
    }
  }

  // 视频元数据提取器
  static Future<Map<String, dynamic>?> extractVideoMetadata(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) return null;

      final videoInfo = FlutterVideoInfo();
      final info = await videoInfo.getVideoInfo(filePath);
      
      if (info == null) return null;

      final metadata = <String, dynamic>{};

      // 基本视频信息
      if (info.duration != null) {
        metadata['duration_seconds'] = info.duration! / 1000.0; // 转换为秒
      }
      
      if (info.width != null) {
        metadata['width'] = info.width;
      }
      
      if (info.height != null) {
        metadata['height'] = info.height;
      }
      
      // flutter_video_info 1.3.3版本暂不支持frameRate
      // 可以通过其他字段推断或使用更高级的库
      // metadata['frame_rate'] = null;
      
      // flutter_video_info不直接提供比特率和编码信息
      // 可以从mimetype推断部分信息
      if (info.mimetype != null) {
        metadata['codec'] = _extractCodecFromMimeType(info.mimetype!);
      }

      return metadata.isNotEmpty ? metadata : null;
    } catch (e) {
      debugPrint('提取视频元数据失败: $filePath - $e');
      return null;
    }
  }

  // 从MIME类型推断编码格式
  static String? _extractCodecFromMimeType(String mimeType) {
    // 例如: "video/mp4" -> "mp4"
    if (mimeType.contains('/')) {
      return mimeType.split('/').last;
    }
    return mimeType;
  }

  // 解析分数格式的值 (如 "24/1" -> 24.0)
  static double? _parseFraction(String value) {
    try {
      if (value.contains('/')) {
        final parts = value.split('/');
        if (parts.length == 2) {
          final numerator = double.tryParse(parts[0]);
          final denominator = double.tryParse(parts[1]);
          if (numerator != null && denominator != null && denominator != 0) {
            return numerator / denominator;
          }
        }
      }
      return double.tryParse(value);
    } catch (e) {
      return null;
    }
  }

  // 解析GPS坐标
  static double? _parseGPS(String coordinate, String direction) {
    try {
      // GPS格式通常是 "[21, 30, 40.5]" 表示 21°30'40.5"
      final cleaned = coordinate.replaceAll('[', '').replaceAll(']', '');
      final parts = cleaned.split(', ');
      
      if (parts.length >= 3) {
        final degrees = double.tryParse(parts[0]) ?? 0.0;
        final minutes = double.tryParse(parts[1]) ?? 0.0;
        final seconds = double.tryParse(parts[2]) ?? 0.0;
        
        double decimal = degrees + (minutes / 60.0) + (seconds / 3600.0);
        
        // 南纬和西经为负值
        if (direction == 'S' || direction == 'W') {
          decimal = -decimal;
        }
        
        return decimal;
      }
    } catch (e) {
      // 解析失败，忽略GPS信息
    }
    return null;
  }

  // 解析EXIF日期时间
  static DateTime? _parseExifDateTime(String dateTimeStr) {
    try {
      // EXIF日期格式通常是 "2023:12:25 14:30:45"
      final cleaned = dateTimeStr.replaceFirst(':', '-').replaceFirst(':', '-');
      return DateTime.tryParse(cleaned.replaceFirst(' ', 'T'));
    } catch (e) {
      return null;
    }
  }
}